Python Functions Notebook

Notation for errors I met.
For quick search

Build in function

A

assert

code:
assert statement
explanation:

1
2
3
4
if statement == True:
continue
else:
report AssertionError

R

readline()

read the first line and begin with second line
data:

1
2
Title,Released,Label,UK Chart Position,US Chart Position,BPI Certification,RIAA Certification
Please Please Me,22 March 1963,Parlophone(UK),1,-,Gold,Platinum

code:

1
2
3
4
with open(datafile, "r") as f:
header = f.readline().split(",")
for line in f:
...

header:
['Title', 'Released', 'Label', 'UK Chart Position', 'US Chart Position', 'BPI Certification', 'RIAA Certification\n']
line:
Please Please Me,22 March 1963,Parlophone(UK),1,-,Gold,Platinum

S

strip()

can be used to delete the \n code
code:

1
2
3
4
header = f.readline().split(",")
print header
print header[-1]
print header[-1].strip()

output:

1
2
3
4
['Title', 'Released', 'Label', 'UK Chart Position', 'US Chart Position', 'BPI Certification', 'RIAA Certification\n']
RIAA Certification
RIAA Certification

Imported modules

csv

csv.DictReader()

read csv file,
default denote the first row as the field labels,
line is dict data type
code:

1
2
3
4
5
import csv
with open(datafile, 'rb') as sd:
r = csv.DictReader(sd)
for line in r:
...

more details can be found in ud032 Using CSV Module

xlrd

xlrd.open_workbook()

read xls file
code:

1
2
3
4
5
6
7
import xlrd
datafile = "2013_ERCOT_Hourly_Load_Data.xls"
workbook = xlrd.open_workbook(datafile)
sheet = workbook.sheet_by_index(0)
data = [[sheet.cell_value(r, col)
for col in range(sheet.ncols)]
for r in range(sheet.nrows)]

details can be found in ud032 Notebook

ZipFile

code:

1
2
from zipfile import ZipFile
datafile = "2013_ERCOT_Hourly_Load_Data.xls"